package repository

import (
	"com.haojuetrace/actualCombat/common"
	"com.haojuetrace/actualCombat/model"
	"database/sql"
	"fmt"
	"time"
)

/*
	操作数据库，分类的创建，删除，修改，查看
*/
type IClassifyRepository interface {
	Create(classify *model.Classify) (err error)
	Updata(classify *model.Classify, id int) (res sql.Result, err error)
	Select(field string, value interface{}) (exist bool, classify *model.Classify)
	Delete(id int) (err error)
}

type ClassifyRepository struct {
	Db *sql.DB
}

//NewClassifyRepository 创建一个ClassifyRepository
func NewClassifyRepository() IClassifyRepository {
	return ClassifyRepository{
		Db: common.GetDb(),
	}
}

//Create 创建分类
func (c ClassifyRepository) Create(classify *model.Classify) (err error) {
	sqlStr := `insert classify (name,createAt,updataAt) values(?,?,?)`
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
	ret, err := c.Db.Exec(sqlStr, classify.Name, time.Now().Format("2006/01/02 15:04:05"), time.Now().Format("2006/01/02 15:04:05"))
	if err != nil {
		fmt.Println("创建分类失败，系统繁忙！", err)
		return err
	}
	id, _ := ret.LastInsertId()
	_, classifys := c.Select("id", id)
	classify.Id = classifys.Id
	classify.Name = classifys.Name
	classify.CreateAt = classifys.CreateAt
	classify.UpdataAt = classifys.UpdataAt
	return err
}

//Updata 修改分类
func (c ClassifyRepository) Updata(classify *model.Classify, id int) (res sql.Result, err error) {
	sqlStr := "UPDATE classify SET name=?,updataAt=? WHERE id=?"
	res, err = c.Db.Exec(sqlStr, classify.Name, time.Now().Format("2006/01/02 15:04:05"), id)
	if err != nil {
		fmt.Println("修改分类失败")
		return nil, err
	}
	_, classifys := c.Select("id", classify.Id)
	classify.UpdataAt = classifys.UpdataAt
	return res, nil
}

//Select 查询分类是否存在
func (c ClassifyRepository) Select(field string, value interface{}) (exist bool, classify *model.Classify) {
	sqlStr := fmt.Sprintf("select id,name,createAt,updataAt from classify where %s=?", field)
	classify = &model.Classify{}
	var cCreateat, cUpdataAt string
	_ = c.Db.QueryRow(sqlStr, value).Scan(&classify.Id, &classify.Name, &cCreateat, &cUpdataAt)
	if classify.Id > 0 {
		classify.CreateAt, _ = time.Parse("2006-01-02 15:04:05", cCreateat)
		classify.UpdataAt, _ = time.Parse("2006-01-02 15:04:05", cUpdataAt)
		return true, classify
	}

	return false, nil
}

//Delete 修改分类
func (c ClassifyRepository) Delete(id int) (err error) {
	sqlStr := "DELETE from classify WHERE id=?"
	_, err = c.Db.Exec(sqlStr, id)
	if err != nil {
		fmt.Println("删除失败")
		return err
	}
	return nil
}
